<template>
  <div class="search-page-container">
    <!-- 顶部导航栏 -->
    <div class="search-header">
      <div class="header-content">
        <!-- 返回按钮 -->
        <a-button 
          class="back-btn" 
          type="text" 
          @click="handleBack"
        >
          <template #icon>
            <ArrowLeftOutlined />
          </template>
          返回
        </a-button>
        
        <!-- 搜索框 -->
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索课程、讲师、学习内容..."
          size="large"
          @search="onSearch"
          @pressEnter="onSearch"
          class="search-input"
          :enter-button="false"
          allowClear
        >
          <template #prefix>
            <SearchOutlined />
          </template>
          <template #suffix></template>
        </a-input-search>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="search-content">
      <!-- 标签页切换 -->
      <a-tabs 
        v-model:activeKey="activeTab" 
        class="search-tabs"
        @change="handleTabChange"
      >
        <a-tab-pane key="comprehensive" tab="综合" />
        <a-tab-pane key="works" tab="作品" />
        <a-tab-pane key="collection" tab="合集" />
        <a-tab-pane key="user" tab="用户" />
        <a-tab-pane key="product" tab="商品" />
      </a-tabs>

      <!-- 搜索结果区域 -->
      <div class="search-results">
        <!-- 综合结果 -->
        <div v-if="activeTab === 'comprehensive'" class="comprehensive-results">
          <div v-if="isLoading" class="loading-container">
            <a-spin size="large" />
          </div>
          
          <div v-else-if="hasResults">
            <!-- 综合结果统计 -->
            <div class="results-stats">
              找到关于「{{ searchKeyword }}」的约 {{ totalResults }} 个结果
            </div>
            
            <!-- 作品 -->
            <div class="result-section" v-if="works.length">
              <h3 class="section-title">相关作品</h3>
              <WorksList 
                :works="works" 
                @work-view="handleWorkView"
              />
            </div>

            <!-- 合集 -->
            <div class="result-section" v-if="collections.length">
              <h3 class="section-title">相关合集</h3>
              <CollectionList 
                :collections="collections"
                @collection-view="handleCollectionView"
              />
            </div>

            <!-- 商品 -->
            <div class="result-section" v-if="products.length">
              <h3 class="section-title">相关商品</h3>
              <ProductList 
                :products="products"
                @product-view="handleProductView"
              />
            </div>

            <!-- 用户 -->
            <div class="result-section" v-if="users.length">
              <h3 class="section-title">相关用户</h3>
              <SearchUserList 
                :users="users"
                @user-view="handleUserView"
              />
            </div>
          </div>
          
          <div v-else class="no-results">
            <SearchOutlined class="no-result-icon" />
            <p>没有找到与「{{ searchKeyword }}」相关的内容</p>
            <p>请尝试其他关键词或搜索条件</p>
          </div>
        </div>

        <!-- 作品结果 -->
        <div v-else-if="activeTab === 'works'">
          <WorksList 
            :works="works" 
            @work-view="handleWorkView"
          />
        </div>

        <!-- 用户结果 -->
        <div v-else-if="activeTab === 'user'">
          <SearchUserList 
            :users="users"
            @user-view="handleUserView"
          />
        </div>

        <!-- 合集结果 -->
        <div v-else-if="activeTab === 'collection'">
          <CollectionList 
            :collections="collections"
            @collection-view="handleCollectionView"
          />
        </div>

        <!-- 商品结果 -->
        <div v-else-if="activeTab === 'product'">
          <ProductList 
            :products="products"
            @product-view="handleProductView"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { SearchOutlined, ArrowLeftOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { searchAll } from '@/specialApi/search/bizSearchController';
import { searchUserByEs } from '@/specialApi/search/bizUserController';
import { searchProductByEs } from '@/specialApi/search/bizProductController';
import { searchWorkByEs } from '@/specialApi/search/bizWorkController';

// 导入子组件
import WorksList from '@/components/search/WorksList.vue';
import CollectionList from '@/components/search/CollectionList.vue';
import ProductList from '@/components/search/ProductList.vue';
import SearchUserList from '@/components/search/SearchUserList.vue';

// 类型定义
interface Product {
  productId: number;
  productName: string;
  price: number;
  mainImage: string;
  sales?: number;
  rating?: number;
  detailImage?: string;
}

interface SearchUserItem {
  id: number;
  avatar?: string;
  username?: string;
  nickname?: string;
  email?: string;
  phone?: string;
  deptName?: string;
}

interface WorkItem {
  id: number;
  worksName: string;
  coverUrl: string;
  description?: string;
  userId?: number;
}

interface CollectionItem {
  id: number;
  name: string;
  coverUrl: string;
  description?: string;
}

// 路由相关
const router = useRouter();
const route = useRoute();

// 状态管理
const initialKeyword = ref(route.query.keyword as string || '');
const searchKeyword = ref(initialKeyword.value);
const activeTab = ref('comprehensive');
const isLoading = ref(false);

// 读取并标准化 MinIO 基础地址
const minioBaseUrl = ((import.meta as any).env?.VITE_MINIO_URL || '').replace(/\/$/, '');
const makeUrl = (p?: string) => {
  if (!p) return '';
  if (/^https?:\/\//i.test(p)) return p;
  const path = p.startsWith('/') ? p : `/${p}`;
  return `${minioBaseUrl}${path}`;
};

// 结果集合
const users = ref<SearchUserItem[]>([]);
const works = ref<WorkItem[]>([]);
const products = ref<Product[]>([]);
const collections = ref<CollectionItem[]>([]);

// 结果统计

const totalResults = computed<number>(() => {
  return works.value.length + 
         products.value.length + 
         users.value.length +
         collections.value.length;
});

const hasResults = computed<boolean>(() => {
  return totalResults.value > 0;
});

// 方法
const handleBack = () => {
  router.push('/'); // 返回主界面
};

const handleSearch = async (value: string) => {
  if (!value.trim()) return;

  searchKeyword.value = value;
  isLoading.value = true;

  try {
    const res = await searchAll({ keyword: value });
    const list = Array.isArray(res) ? res : (Array.isArray((res as any)?.data) ? (res as any).data : []);

    // 重置
    users.value = [];
    works.value = [];
    products.value = [];
    collections.value = [];

    list.forEach((item: any) => {
      const t = item?.type || item?.data?.type;
      const d = item?.data || {};
      if (!t) return;

      if (t === 'biz_user' || t === 'sys_user') {
        users.value.push({
          id: Number(d.user_id ?? d.id ?? 0),
          avatar: makeUrl(String(d.file_path || d.business_img || '')),
          username: d.username ? String(d.username) : undefined,
          nickname: d.nickname ? String(d.nickname) : undefined,
          email: d.email ? String(d.email) : undefined,
          phone: d.phone ? String(d.phone) : undefined,
          deptName: d.dept_name ? String(d.dept_name) : undefined,
        });
      } else if (t === 'biz_works') {
        works.value.push({
          id: Number(d.id ?? 0),
          worksName: String(d.works_name || ''),
          coverUrl: makeUrl(String(d.cover_file_url || '')),
          description: String(d.description || ''),
          userId: Number(d.user_id ?? 0)
        });
      } else if (t === 'biz_product' || t === 'biz_products') {
        products.value.push({
          productId: Number(d.product_id ?? d.id ?? 0),
          productName: String(d.product_name || ''),
          price: Number(d.price ?? 0),
          mainImage: makeUrl(String(d.main_image || '')),
          sales: Number(d.sale ?? 0),
          rating: 0,
          detailImage: makeUrl(String(d.detail_image || ''))
        });
      } else if (t === 'media_colletcion' || t === 'biz_collection') {
        collections.value.push({
          id: Number(d.id ?? 0),
          name: String(d.name || d.works_name || ''),
          coverUrl: makeUrl(String(d.cover_url || d.cover_file_url || '')),
          description: String(d.description || d.work_description || '')
        });
      }
    });
  } catch (e) {
    message.error('搜索失败，请稍后再试');
  } finally {
    isLoading.value = false;
  }
};

// 统一触发器，确保多次点击或按回车都能触发最新关键词
const onSearch = () => {
  handleSearch(searchKeyword.value || '');
};

const handleTabChange = (key: string) => {
  activeTab.value = key;
  // 根据标签页切换加载对应的数据
  if (searchKeyword.value.trim()) {
    loadTabSpecificData(key, searchKeyword.value);
  }
};

// 加载标签页特定的数据
const loadTabSpecificData = async (tab: string, keyword: string) => {
  if (!keyword.trim()) return;

  isLoading.value = true;
  try {
    if (tab === 'user') {
      const res = await searchUserByEs({ keyword, page: 1, size: 50 });
      const data = (res && (res as any).data) ? (res as any).data : res;
      const hits = (data && Array.isArray(data.hits)) ? data.hits : [];
      
      users.value = hits.map((h: any) => {
        const src = h?.source || {};
        return {
          id: Number(src.user_id ?? src.id ?? h?.id ?? 0),
          avatar: makeUrl(String(src.file_path || src.business_img || '')),
          username: src.username ? String(src.username) : undefined,
          nickname: src.nickname ? String(src.nickname) : undefined,
          email: src.email ? String(src.email) : undefined,
          phone: src.phone ? String(src.phone) : undefined,
          deptName: src.dept_name ? String(src.dept_name) : undefined,
        };
      });
    } else if (tab === 'product') {
      const res = await searchProductByEs({ keyword, page: 1, size: 50 });
      const data = (res && (res as any).data) ? (res as any).data : res;
      const hits = (data && Array.isArray(data.hits)) ? data.hits : [];
      
      products.value = hits.map((h: any) => {
        const src = h?.source || {};
        return {
          productId: Number(src.product_id ?? src.id ?? 0),
          productName: String(src.product_name || ''),
          price: Number(src.price ?? 0),
          mainImage: makeUrl(String(src.main_image || '')),
          sales: Number(src.sale ?? 0),
          rating: 0,
          detailImage: makeUrl(String(src.detail_image || ''))
        };
      });
    } else if (tab === 'works') {
      const res = await searchWorkByEs({ keyword, page: 1, size: 50 });
      const data = (res && (res as any).data) ? (res as any).data : res;
      const hits = (data && Array.isArray(data.hits)) ? data.hits : [];
      
      works.value = hits.map((h: any) => {
        const src = h?.source || {};
        return {
          id: Number(src.id ?? 0),
          worksName: String(src.works_name || ''),
          coverUrl: makeUrl(String(src.cover_file_url || '')),
          description: String(src.description || ''),
          userId: Number(src.user_id ?? 0),
          isCharge: Number(src.is_charge ?? 0),
          price: Number(src.price ?? 0)
        };
      });
    }
  } catch (e) {
    message.error('加载数据失败，请稍后再试');
  } finally {
    isLoading.value = false;
  }
};

const handleWorkView = (work: WorkItem) => {
  console.log('查看作品:', work.worksName);
  message.success(`查看作品: ${work.worksName}`);
};

const handleProductView = (product: Product) => {
  console.log('查看商品:', product.productName);
  message.success(`查看商品详情: ${product.productName}`);
};

const handleCollectionView = (collection: CollectionItem) => {
  console.log('查看合集:', collection.name);
  message.success(`查看合集: ${collection.name}`);
};

const handleUserView = (user: SearchUserItem) => {
  const display = user.nickname || user.username || user.email || user.phone || '用户';
  console.log('查看用户:', display);
  // 跳转到访客查看用户页面
  router.push(`/visitor/${user.id}`);
};

// 初始化
onMounted(() => {
  if (initialKeyword.value) {
    handleSearch(initialKeyword.value);
  }
});
</script>

<style scoped>
.search-page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
  color: #fff;
  padding-bottom: 40px;
}

/* 头部样式 */
.search-header {
  background: rgba(26, 26, 46, 0.9);
  backdrop-filter: blur(15px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.15);
  padding: 12px 24px;
}

.header-content {
  display: flex;
  align-items: center;
  max-width: 1400px;
  margin: 0 auto;
}

.back-btn {
  color: #ddd !important;
  margin-right: 16px !important;
  padding: 0 8px !important;
  font-size: 18px !important;
}

.back-btn:hover {
  color: #fff !important;
  background: rgba(255, 255, 255, 0.1) !important;
}

.search-input {
  flex: 1;
  max-width: 800px;
  border-radius: 20px !important;
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
}

.search-input :deep(.ant-input-affix-wrapper) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
  height: 44px !important;
  border-radius: 20px !important;
  padding: 0 12px !important;
}

.search-input :deep(.ant-input-affix-wrapper:hover),
.search-input :deep(.ant-input-affix-wrapper-focused) {
  background: rgba(255, 255, 255, 0.12) !important;
  box-shadow: 0 0 0 2px rgba(255, 71, 87, 0.25) !important;
}

.search-input :deep(.ant-input) {
  background: transparent !important;
  color: #fff !important;
  height: 40px !important;
}

.search-input :deep(.ant-input::placeholder) {
  color: rgba(255, 255, 255, 0.6) !important;
}

.search-input :deep(.ant-input-prefix) {
  color: rgba(255, 255, 255, 0.85) !important;
}

.search-input :deep(.ant-input-suffix) {
  color: rgba(255, 255, 255, 0.6) !important;
}

.search-input :deep(.ant-input-clear-icon) {
  color: rgba(255, 255, 255, 0.75) !important;
}

/* 强制隐藏 antd 自带的搜索按钮（即便被注入） */
.search-input :deep(.ant-input-search-button) {
  display: none !important;
}

/* 统一右侧搜索按钮风格 */
/* 删除了右侧 button，因此去除对应样式 */

/* 内容区域 */
.search-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
}

/* 标签页样式 */
.search-tabs {
  margin-bottom: 24px !important;
  background: rgba(22, 33, 62, 0.8) !important;
  border-radius: 8px !important;
  padding: 8px !important;
  border: 1px solid rgba(255, 255, 255, 0.15) !important;
}

.search-tabs :deep(.ant-tabs-nav) {
  margin: 0 !important;
}

.search-tabs :deep(.ant-tabs-tab) {
  color: #ddd !important;
  padding: 8px 16px !important;
  margin: 0 4px !important;
}

.search-tabs :deep(.ant-tabs-tab-active) {
  color: #ff4757 !important;
  background: rgba(255, 71, 87, 0.1) !important;
  border-radius: 6px !important;
}

.search-tabs :deep(.ant-tabs-ink-bar) {
  background: #ff4757 !important;
}

/* 搜索结果样式 */
.search-results {
  background: rgba(22, 33, 62, 0.8);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  padding: 24px;
  min-height: 400px;
}

.results-stats {
  color: #ddd;
  font-size: 14px;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.result-section {
  margin-bottom: 32px;
}

.result-section:last-child {
  margin-bottom: 0;
}

.section-title {
  color: #fff;
  font-size: 18px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}

.section-title::after {
  content: '';
  flex: 1;
  height: 1px;
  background: linear-gradient(to right, rgba(255, 71, 87, 0.5), transparent);
  margin-left: 12px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.loading-container :deep(.ant-spin-dot-item) {
  background-color: #ff4757 !important;
}

/* 无结果状态 */
.no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  color: #999;
}

.no-result-icon {
  font-size: 60px;
  color: rgba(255, 255, 255, 0.2);
  margin-bottom: 24px;
}

.no-results p {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.no-results p:last-child {
  font-size: 14px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-header {
    padding: 8px 16px;
  }
  
  .search-content {
    padding: 16px;
  }
  
  .search-results {
    padding: 16px;
  }
  
  .search-tabs :deep(.ant-tabs-tab) {
    padding: 6px 12px !important;
    font-size: 14px !important;
  }
}
</style>
